/**
 * webscoket
 */

import { Message, Loading } from 'element-ui'
import { nanoid } from 'nanoid'
import store from '@/store';
// 基本参数
const ConnectionParams = {
    reqId: nanoid(8),
    operation: 1000,
    screenId: "screen_1",
}
let wsClient;
const WebSocketURL = "ws://" + location.host + "/ws";

if ("WebSocket" in window) {
    wsClient = new WebSocket(WebSocketURL);
} else {

}
// 打开连接
wsClient.onopen = function(event) {
    switch (wsClient.readyState) {
        case 1:
            wsClient.send(JSON.stringify(ConnectionParams));
            break;
        default:
            break;
    }
}
//连接发生错误的回调方法
wsClient.onerror = function() {
    console.log('连接错误');
};
//接收到消息的回调方法
wsClient.onmessage = function(event) {
    console.log(event);
    const Data = JSON.parse(event.data)
    console.log(Data);
    switch (Number(Data.operation)) {
        case 1000:
            ConnectionParams.operation = 4000
            wsClient.send(JSON.stringify(ConnectionParams));
            break;
        case 4000:
            store.commit("INIT_SCREEN", Data.data)
            break;
        case 4003:
            store.commit("UPDATA_SCREEN", Data.data)
            break;
        case 3001:
            store.commit("SELECT_MODULE", Data)
            console.log(Data, '选中模块');
            break;
        case 3002:
            console.log(Data, '取消选中模块');
            store.commit("CANCEL_MODULE", Data)
            break;
        case 3000:
            console.log(Data, '发送事件');
            store.commit("ISSUED_EVENT", Data)
            break;
        default:
            break;
    }
}

// 监听VueX事件变化并发送消息
store.subscribeAction((mutation, state) => {
    // console.log(mutation)
    // console.log(state)
    // console.log('这里是websocket');
    if (mutation.type === "SEND_PARAMS") {
        wsClient.send(JSON.stringify(mutation.payload))
    }
})